package com.xiaodao.springboot.services;

import com.xiaodao.springboot.utility.ObjectSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class ObjectCacheService {

    @Value("${storage.base-path}")
    private String basePath;

    @Cacheable(value = "objectCache", key = "#objectId")
    public <T> T getObject(String objectId, Class<T> type) throws IOException {
        Path path = getObjectPath(objectId);
        System.out.println("Loading from file: " + path);
        return ObjectSerializer.readFromFile(path, type);
    }

    @CachePut(value = "objectCache", key = "#objectId")
    public <T> T saveObject(String objectId, T obj) throws IOException {
        Path path = getObjectPath(objectId);
        ObjectSerializer.writeToFile(obj, path);
        return obj;
    }

    @CacheEvict(value = "objectCache", key = "#objectId")
    public void deleteObject(String objectId) throws IOException {
        Path path = getObjectPath(objectId);
        Files.deleteIfExists(path);
    }

    private Path getObjectPath(String objectId) {
        return Paths.get(basePath, objectId + ".json");
    }
}
